<template>
  <view class="userBind">

		<u-popup class="popup" v-model="show" mode="center" :round="10" width="100%" height="100%" @open="open" @close="handleClose">
      <view class="comPopWrapHd">
        <u-icon name="arrow-left" class="icon_arrow" color="#000" size="45" @click="handleClose"></u-icon>
        <view class="title">绑定老人</view>
      </view>
      <view class="main">
        <view class="comPopWrap">
          <u-form :model="form" ref="uForm" class="uForm" label-position="top" :border-bottom="false" :error-type="errorType" labelWidth="150">
            <u-form-item label="我对老人的称呼" :border-bottom="false" prop="notes">
              <u-input v-model="form.notes" border placeholder="请输入我对老人的称呼" clearable />
            </u-form-item>
            <u-form-item label="老人对我的称呼" :border-bottom="false" prop="userNotes">
              <u-input v-model="form.userNotes" border placeholder="请输入老人对我的称呼" clearable />
            </u-form-item>

            <template v-if="!edit">
              <u-form-item label="关系" :border-bottom="false" prop="relationship">
                <u-input v-model="form.relationship" border @click="showRelationship = true" type="select" placeholder="请选择和老人的关系" clearable />
                <u-select v-model="showRelationship" mode="mutil-column-auto" :list="relationshipList" @confirm="(e)=>fConfirm(e, 'relationship')"></u-select>
              </u-form-item>
              <u-form-item label="手机号" :border-bottom="false" prop="phone">
                <u-input v-model="form.phone" border maxlength="11" placeholder="请输入老人手机号" clearable />
              </u-form-item>
              <u-form-item label="验证码" :border-bottom="false" prop="captcha">
                <view class="captcha">
                  <u-input v-model="form.captcha" border maxlength="6" placeholder="请输入验证码" clearable />
                  <!-- <u-button size="mini" slot="right" style="background: none !important;border:0 !important;color: #2761FF;" @click="fGetCode">{{ codetip }}</u-button> -->
                  <text class="code" @click="fGetCode">{{ codetip }}</text>
                </view>
              </u-form-item>
              <u-form-item label="类型" :border-bottom="false" prop="urgent">
                <u-input v-model="form.urgent" border @click="showUrgent = true" type="select" placeholder="请选择类型" clearable />
                <u-select v-model="showUrgent" mode="mutil-column-auto" :list="urgentList" @confirm="(e)=>fConfirm(e, 'urgentList')"></u-select>
              </u-form-item>
            </template>
          </u-form>
        </view>

        <view class="ft">
          <view class="btn" @click="handleConfirm">绑定</view>
        </view>
      </view>
		</u-popup>
	</view>
</template>

<script>
import md5 from '@/utils/md5.js'
import sha1 from '@/utils/sha1.js'
import { userBind, genApiKey, userNotesUpdate } from "@/api"

export default {
  name: "DialogUserBind",
  props: {
    edit: {
      type: Boolean,
      default: false
    },
    showPop: {
      type: Boolean,
      default: true
    },
    userData: {
      type: Object,
      default: {}
    }
  },
  computed: {
    show: {
      get() {
        return this.showPop
      },
      set(value) {
        this.$emit('update:showPop', value)
      }
    }
  },
  onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
  data() {
    return {
      form: {
        notes: '',
        userNotes: '',
        relationship: null,
        phone: '',
        captcha: '',
        urgent: null
      },
      userId: null,
      relationship: null,
      urgent: null,
      showRelationship: false,
      relationshipList: [{
        value: 1,
        label: '子女'
      },{
        value: 2,
        label: '配偶'
      },{
        value: 3,
        label: '亲戚'
      }],
      showUrgent: false,
      urgentList: [{
        value: 1,
        label: '紧急'
      },{
        value: 2,
        label: '不紧急'
      }],
      isDisabled: true,
      codetip: '获取验证码',
      errorType: ['toast'],
      rules: {
        notes: [
					{ 
            required: true,
						message: '请输入对老人的称呼', 
						trigger: ['change','blur']
					}
				],
        relationship: [
					{ 
            required: true,
						message: '请选择和老人的关系', 
						trigger: ['change','blur']
					}
				],
				phone: [
					{
            required: true,
						message: '请输入手机号', 
						trigger: ['change','blur']
					},
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value);
            },
            message: '电话号码格式不正确',
            trigger: ['change','blur'],
          }
				],
				captcha: [
					{ 
            required: true,
						message: '请输入验证码', 
						trigger: ['change','blur']
					}
				]
			}
    }
  },
  methods: {
    open(){
      if(this.edit){
        this.userId = this.userData.userId
        this.form.notes = this.userData.notes
        this.form.userNotes = this.userData.userNotes
      }
    },
    handleClose() {
      this.show = false
      this.$emit('close')
    },
    fConfirm(val, type){
      console.log(val)
      if(val){
        if(type == 'relationship'){
          this.relationship = val[0].value
          this.form.relationship = val[0].label
        } else{
          this.urgent = val[0].value
          this.form.urgent = val[0].label
        }
      }
    },
    handleConfirm(){
      let _this = this
      this.$refs.uForm.validate(valid => {
				if (valid) {
          let data = {}
          
          if(this.edit){
            data = {
              userId: this.userId,
              notes: this.form.notes,
              userNotes: this.form.userNotes
            }
          }else{
            data = {
              ...this.form,
              relationship: this.relationship,
              urgent: this.urgent
            }
          }

          let Fn = this.edit ? userNotesUpdate : userBind
          Fn(data).then(res => {
            if(res.code === 0){
              uni.showToast({
                title: '保存成功！',
                icon: 'success',
                duration: 3000
              })
              setTimeout(function(){
                _this.handleClose()
                _this.$emit('save')
              }, 3000)
            }
          })
        }
      })
    },
    RandNum() {  // 8位随机数
      let rand = ''
      for(let i=0;i<8;i++){
        rand += Math.floor(Math.random()*10)
      }
      return rand;
    },
    mod(n, m) {  // 取模
      return ((n % m) + m) % m;
    },
    fGetCode() {  // 获取验证码
      if(this.isDisabled == false){
        return
      }
      if(this.form.phone == ''){
        return uni.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 3000
        })
      }
      // 获取密钥key
      genApiKey().then(res => {
        let _this = this
        if(res.code === 0){
          const xKey = res.data;
          let nonce = this.RandNum()
          let sha1_key = '', md5_nonce = '', sign = '', x = null
          
          // 1、对密钥key使用 sha1加密 得到 sha1_key
          sha1_key = sha1.sha1(xKey)

          // 2、对随机数使用md5 加密 得到 md5_nonce
          md5_nonce = md5(nonce)

          // 3、nonce 对8取模 得到 x
          x = this.mod(nonce, 8)

          // 4、sha1_key的第x位和md5_nonce的第x位交换
          let s = sha1_key.charAt(x)  // sha1_key第x位
          let m = md5_nonce.charAt(x) // md5_nonce第x位
          // sha1_key的第x位和md5_nonce的第x位交换
          sha1_key = sha1_key.substr(0, x) + m + sha1_key.substr(x + 1);
          md5_nonce = md5_nonce.substr(0, x) + s + md5_nonce.substr(x + 1);

          // 5、sign = md5（ 交换位置后的sha1_key + 交换位置后的
          sign = md5(sha1_key + md5_nonce)

          // 发送验证码
          wx.request({
            url: 'https://eldertab-test-guardian.hpaiapp.com/user/sendCheck',
            method: 'POST',
            header: {
              'x-key': xKey, // apikey接口给的密钥
              'x-nonce': nonce, // 8位随机数
              'x-sign': sign, // 签名
            },
            data: {
              sendType: 1, // 类型0: 注册 1: 绑定
              phone: this.form.phone
            },
            success(){
              uni.showToast({
                title: '发送成功',
                icon: 'success',
                duration: 3000
              })
              _this.fCountdown()
            }
          })
        }
      })
    },
    fCountdown(){
      // 控制倒计时期间不可再点击
      if(this.isDisabled == false){
        return
      }
      this.isDisabled = false
      let count = 60
      let timer = setInterval(()=>{
        count--
        if(count==0){
          this.codetip = '重新获取'
          this.isDisabled = true
          clearInterval(timer)
        }else{
          this.codetip = `${count}秒后重发`
        }
      },1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.userBind{
  padding: 20rpx 25rpx;
}

.main{
  height: 100%;
  padding: 20rpx 25rpx;
  background: #F7F7F7;
}

.comPopWrap{
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx 40rpx;

  .captcha{
    position: relative;
  }
  .code{
    color: #2761FF;
    font-size: 24rpx;
    position: absolute;
    top: 3rpx;
    right: 20rpx;
    z-index: 999;
  }
}

.ft{
  width: 100%;
  margin-top: 80rpx;

  .btn{
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 88rpx;
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
    text-align: center;
    margin: 40rpx 60rpx;
    background: #2761FF;
  }
}

::v-deep .u-input--border, ::v-deep.u-input{
  border-radius: 44rpx !important;
}
</style>